package com.ssy.system.controller;

import cn.hutool.captcha.CaptchaUtil;
import cn.hutool.captcha.CircleCaptcha;
import cn.hutool.http.useragent.UserAgent;
import cn.hutool.http.useragent.UserAgentUtil;
import com.ssy.common.CodeMsg;
import com.ssy.common.Constant;
import com.ssy.common.utils.ActiveUser;
import com.ssy.common.utils.Result;
import com.ssy.system.pojo.Log;
import com.ssy.system.pojo.User;
import com.ssy.system.service.ILogService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.Date;

/**
 * @author sunshuaiyong
 * @ClassName LoginController
 * @description: TODO
 * @date 2021/10/28 13:59
 */
@RestController
@RequestMapping("/login")
public class LoginController {

    @Autowired
    private ILogService logService;

    @PostMapping("/userLogin")
    public Result userLogin(User user, HttpServletRequest request) {
        //获取session中的验证码
        String code = (String) request.getSession().getAttribute(Constant.SESSION_VERIFICATION_CODE);
        //校验验证码
        if (!code.equals(user.getCode())) {
            return new Result(CodeMsg.LOGIN_CODE_ERROR);
        }

        //获取主体
        try {
            Subject subject = SecurityUtils.getSubject();
            UsernamePasswordToken token = new UsernamePasswordToken(user.getUserName(), user.getPassword());
            //登录
            subject.login(token);

            //将user放入session中
            ActiveUser activeUser = (ActiveUser) subject.getPrincipal();
            request.getSession().setAttribute(Constant.SESSION_CURRENT_USER, activeUser.getUser());

            //写入登录日志
            User user1 = activeUser.getUser();
            Log log = new Log();
            log.setUserId(user1.getId());
            log.setUserName(user1.getUserName());
            log.setRealName(user1.getRealName());
            log.setLoginStart(1);
            log.setLoginType(user1.getType());
            log.setIp(request.getRemoteAddr());

            UserAgent ua = UserAgentUtil.parse(request.getHeader("User-Agent"));

            log.setBrowser(ua.getBrowser().toString());
            log.setSystem(ua.getOs().toString());
            log.setLoginTime(new Date());
            this.logService.insertLog(log);
            return new Result(CodeMsg.LOGIN_SUCCESS);

        } catch (Exception e) {
            e.printStackTrace();
            return new Result(CodeMsg.LOGIN_PASSWORD_USERNAME_ERROR);
        }

    }

    /**
     * 图形验证码
     *
     * @param req  Request
     * @param resp Response
     * @throws IOException
     */
    @GetMapping("/verificationCode")
    public void verificationCode(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        CircleCaptcha checkCode = CaptchaUtil.createCircleCaptcha(86, 44, 1, 10);
        String code = checkCode.getCode();
        System.out.println(code);

        //将验证码存放session中
        req.getSession().setAttribute(Constant.SESSION_VERIFICATION_CODE, code);
        checkCode.write(resp.getOutputStream());//输出到页面
    }


}
